package com.mycompany.projektjava;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Ondřej Myška
 */
public class CarDAOImpl implements CarDAO {

    private EntityManagerFactory emf;

    public CarDAOImpl(/*String persistenceUnit*/) {
        //emf = Persistence.createEntityManagerFactory(persistenceUnit);
        emf = Persistence.createEntityManagerFactory("TestPU");
    }

    public void createCar(Car car) {
        if (car != null) {
            EntityManager em = emf.createEntityManager();

            em.getTransaction().begin();
            em.persist(car);
            em.getTransaction().commit();
            em.close();
        }

    }

    public void remove(Car car) {
        if (car != null) {
            EntityManager em = emf.createEntityManager();

            em.getTransaction().begin();
            em.remove(car);
            em.getTransaction().commit();
            em.close();
        }
    }

    public boolean update(Car car) {
        if (car != null) {
            EntityManager em = emf.createEntityManager();

            em.getTransaction().begin();
            em.persist(em.merge(car));
            em.getTransaction().commit();
            em.close();
            return true;
        }
        return false;
    }

    public Car find(Long id) {
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        Car c = (Car) em.find(Car.class, id);
        em.getTransaction().commit();
        em.close();
        return c;
    }

    public List<Car> getAllCars() {
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        List<Car> l = em.createQuery("Select c FROM Car c").getResultList();
        em.getTransaction().commit();
        em.close();
        return l;
    }


    // vypíše všechny dostupné auta -available=1
    public List<Car> getAllAvailableCars() {
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        List<Car> l = em.createQuery("Select c FROM Car c WHERE c.available=1").getResultList();
        em.getTransaction().commit();
        em.close();
        return l;
    }

    public Car getCar(String spz) {
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        Query q = em.createQuery("Select c FROM Car c WHERE c.spz=?1");
        q.setParameter(1, spz);
        Car c = (Car) q.getSingleResult();
        em.getTransaction().commit();
        em.close();
        return c;
    }

}
